<template>
  <div class="container">
    <el-form ref="formRef" :model="form" :rules="rules" v-loading="loading" label-width="150px" :validate-on-rule-change="false">
      <el-divider content-position="left"><span class="title-left-color">基本信息</span></el-divider>
      <el-row :gutter="10">
        <el-col :span="10">
          <el-form-item label="计划名称：" prop="plan_name">
            <el-input v-model="form.plan_name" :disabled="form.id !== 0" placeholder="请填写计划名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="计划联系人手机号：" prop="merchant_phone">
            <el-input v-model.trim="form.merchant_phone" placeholder="请填写计划联系人手机号"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="10">
          <el-form-item label="带货场景：" prop="content_type">
            <el-select v-model.trim="form.content_type" placeholder="带货场景" clearable :disabled="form.id !== 0" @change="handleChangeContentType">
              <el-option v-for="item in contentType" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10" v-if="form.content_type == '1'">
          <el-form-item label="佣金有效期：" prop="commission_duration">
            <el-input v-model.number="form.commission_duration" :disabled="form.id !== 0" placeholder="请填写佣金有效期"> <template #append>天</template></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="10">
          <el-form-item label="上传投稿视频时间：" prop="start_time">
            <el-date-picker v-model="queryDate" type="datetimerange" range-separator="至" format="YYYY-MM-DD HH:mm:ss" value-format="X" start-placeholder="开始时间" @change="changeQueryDate" end-placeholder="结束时间"> </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left"><span class="title-left-color">达人抖音号信息</span></el-divider>
      <el-row :gutter="10">
        <el-col :span="10">
          <el-form-item label="达人抖音号：" prop="douyin_id_list">
            <div class="tags-info">
              <el-tag :key="tag" v-for="tag in form.douyin_id_list" closable :disable-transitions="false" size="large" @close="handleClose(tag)">
                {{ tag }}
              </el-tag>
              <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" @keyup.enter="handleInputConfirm" @blur="handleInputConfirm"> </el-input>
              <el-button v-else class="button-new-tag" :icon="Plus" @click="handleShowInput">新增抖音号</el-button>
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-divider content-position="left"><span class="title-left-color">商品信息</span></el-divider>
      <el-space wrap class="mb20">
        <el-button type="primary" :icon="Plus" :disabled="disabledbtn" @click="handleAddGoodsData">新增</el-button>
      </el-space>
      <el-table :data="form.goods_list" border class="table" ref="selectGoodsMultipleTableRef" :reserve-selection="true">
        <el-table-column type="index" align="center"> </el-table-column>
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="original_img" label="图片" width="150" align="center">
          <template #default="scope">
            <el-image style="width: 60px; height: 60px" :src="IMG_URL + scope.row.original_img"> </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="goods_name" label="商品名称" align="center"> </el-table-column>
        <el-table-column prop="commission_rate" label="定向抽佣率" align="center">
          <template #default="scope">
            <div class="">
              <el-input v-model.trim="scope.row.commission_rate" placeholder="请输入定向抽佣率"><template #append>天</template></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <div class="mlr10 display-inline-block" v-if="scope.row.isPermitDelete">
              <el-popconfirm placement="top" width="160" title="你确定要删除吗?" @confirm="handleDeleteGoods(scope.row)">
                <template #reference>
                  <el-button link :icon="Delete" type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <div class="footer-center">
      <el-button :disabled="disabledbtn" @click="cancelSubmit">取 消</el-button>
      <el-button type="primary" :disabled="disabledbtn" v-if="!isDisabledbtn" @click="submitForm">确 定</el-button>
    </div>
  </div>

  <SelectGoodsDialog :platforms="['douyinPlatform']" :showPlatform="false" selectNumber="more" v-model:edit-visible="goodsVisible" @handleSuccess="handleSelectSuccess" />
</template>

<script setup lang="ts">
import SelectGoodsDialog from "@/components/rentMachineManage/phoneInfo/SelectGoodsDialog.vue";
import { IMG_URL } from "@/utils/config";
import { Delete, Plus } from "@element-plus/icons-vue";
import type { postOrPutType } from "@/constants";
import type { HasId, ViewMode } from "@/types/common";
import type { FormRules, TableInstance } from "element-plus";
import { useState } from "@/hooks/useState.ts";
import type { IMallCategory } from "@/types/mallCategory";
import { getMallCategoryInfo } from "@/utils/api/mallCategory";
import type { ITargetedCommissionPlandGoods, ITargetedCommissionPlanDOT, ITargetedCommissionPlanVO } from "@/types/douyinManager/targetedCommissionPlan";
import type { IDictData } from "@/types/dict";
import { mobildVerify } from "@/utils/utils";
import type { IGoodsList } from "@/types/rentMachineManage/phoneInfo";
import { commonDouyinOrientedCpsInfo, getDouyinOrientedCpsByIdInfo } from "@/utils/api/douyinOrientedCps";
const { disabledbtn, loading, toggleState } = useState();
interface Props {
  id: number;
  contentType: Array<IDictData>;
}
const { id, contentType } = defineProps<Props>();
const formStatus = defineModel<ViewMode>("formStatus", { required: true });

const emit = defineEmits<{
  handleInitData: [];
  handleSuccess: [];
}>();
/* 商品分类 */
const selectCategories = ref<Array<IMallCategory>>([]);
const isDisabledbtn = ref(false);
const goodsVisible = ref(false);

const queryDate = ref<Array<string>>([]);
const formRef = useTemplateRef("formRef");
const selectGoodsMultipleTableRef = ref<TableInstance>();
const methodType = ref<postOrPutType>("PUT");
const form = reactive<ITargetedCommissionPlanDOT>({
  id: 0,
  plan_name: "",
  merchant_phone: "",
  content_type: "",
  start_time: "",
  end_time: "",
  commission_duration: 0,
  douyin_id_list: [],
  goods_list: []
});
const deleteDouyinIdList = ref<string[]>([]);
const inputVisible = ref<boolean>(false);
const inputValue = ref<string>("");
const saveTagInput = useTemplateRef("saveTagInput");

const rules = reactive<FormRules<ITargetedCommissionPlanDOT>>({
  plan_name: [{ required: true, message: "请填写计划名称", trigger: "blur" }],
  merchant_phone: [{ required: true, validator: mobildVerify, trigger: "blur" }],
  content_type: [{ required: true, message: "请选择带货场景", trigger: "blur" }],
  douyin_id_list: [{ required: true, message: "请添加抖音达人号", trigger: "blur" }],
  commission_duration: [],
  start_time: []
});

/* formStatus处理器 */
const statusHandlers: Record<ViewMode, () => void> = {
  view: () => {
    isDisabledbtn.value = true;
  },
  edit: () => {
    methodType.value = "PUT";
  },
  add: () => {
    methodType.value = "POST";
  },
  none: () => {
    /* 初始化数据 */
    handleInitData();
  }
};
/* 监听formStatus,新增，编辑，查看的时候都可以打开模态框，又是有不同的操作和效果，需要单独判断，none为模态框关闭的情况，需要初始化数据 */
watch(formStatus, newValue => {
  const handler = statusHandlers[newValue];
  handler?.();
});
/*  */
watch(
  () => id,
  newValue => {
    if (newValue == 0) {
      /* 初始化数据 */
    } else {
      form.id = newValue;
      handleGetMallRedPacketPurchaseByIdInfo(id);
    }
  }
);
/* 查询 创建时间更改事件 */
function changeQueryDate(data: number[]) {
  if (data !== null) {
    form.start_time = data[0] * 1000;
    form.end_time = data[1] * 1000;
  } else {
    form.start_time = "";
    form.end_time = "";
  }
}
/* 获取分类信息 */
function handleGetMallCategory() {
  getMallCategoryInfo<Array<IMallCategory>, unknown>()
    .then(res => {
      selectCategories.value = res.result;
    })
    .finally(() => {});
}
/* 获取活动详情信息 */
function handleGetMallRedPacketPurchaseByIdInfo(id: number) {
  toggleState(true);
  getDouyinOrientedCpsByIdInfo<ITargetedCommissionPlanVO, HasId>({ id })
    .then(res => {
      form.id = res.result.id;
      res.result.goods_list.forEach(item => {
        item.id = item.goods_id;
        /* 是否允许删除 */
        item.isPermitDelete = false;
      });

      form.goods_list = res.result.goods_list;
      form.douyin_id_list = res.result.talent_status_map.filter(item => item.status != 3).map(item => item.talent_douyin_id);

      /* 删除的抖音id */
      deleteDouyinIdList.value = res.result.talent_status_map.filter(item => item.status == 3).map(item => item.talent_douyin_id);

      form.content_type = res.result.content_type + "";
      form.plan_name = res.result.plan_name;
      form.merchant_phone = res.result.merchant_phone;
      form.commission_duration = res.result.commission_duration;

      if (res.result.content_type == 1) {
        form.start_time = new Date(res.result.start_time).valueOf();
        form.end_time = new Date(res.result.end_time).valueOf();
        queryDate.value.push(form.start_time + "");
        queryDate.value.push(form.end_time + "");
      }
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 初始化数据 */
function handleInitData() {
  methodType.value = "POST";
  isDisabledbtn.value = false;

  inputVisible.value = false;

  form.id = 0;
  form.goods_list = [];
  queryDate.value = [];
  formRef.value?.resetFields();
  formRef.value?.clearValidate();
}

/* 保存校验数据 */
function handleValidate() {
  return true;
}

/* 保存或编辑 */
function submitForm() {
  if (!formRef.value) return;
  formRef.value.validate(valid => {
    if (!valid) {
      ElMessage.warning("请填写必填字段");
      return;
    }
    if (!handleValidate()) return;
    submitFormInfo();
  });
}

/* 保存或编辑信息 */
function submitFormInfo() {
  /* 防止多次提交 */
  toggleState(true);
  commonDouyinOrientedCpsInfo(form, methodType.value)
    .then(res => {
      ElMessage.success(res.msg);
      cancelSubmit();
      emit("handleSuccess");
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 保存或编辑 取消提交 */
function cancelSubmit() {
  // clearData();
  // activeName = "one";
  emit("handleInitData");
}

/* 选择带货场景 */
function handleChangeContentType(data: string) {
  if (data == "2") {
    /* 仅短视频 */
    rules.commission_duration = [];
    rules.start_time = [];
    form.commission_duration = 0;
    form.start_time = "";
    form.end_time = "";
  } else if (data == "1" || data == "3") {
    /* 仅直播间 */
    rules.commission_duration = [{ required: true, validator: mobildVerify, trigger: "blur" }];
    rules.start_time = [{ required: true, message: "请选择上传投稿视频时间", trigger: "blur" }];
  }
}
/* 本地商品排序 */
function handleLocalSort() {
  form.goods_list.sort((a: ITargetedCommissionPlandGoods, b: ITargetedCommissionPlandGoods) => b.sort - a.sort);
}
/* 打开模态框选择新增商品 */
function handleAddGoodsData() {
  goodsVisible.value = true;
}

/* 删除商品信息 */
function handleDeleteGoods(row: ITargetedCommissionPlandGoods) {
  const index = form.goods_list.findIndex((item: ITargetedCommissionPlandGoods) => item.goods_id === row.goods_id);
  if (index != -1) {
    form.goods_list.splice(index, 1);
  }
}

/* 选中数据 */
function handleSelectSuccess(data: IGoodsList[]) {
  for (const item of data) {
    if (!handleIsSelectedGoods(item)) {
      handleAddGoodsList(item);
    }
  }

  handleLocalSort();
}
/* 判断 goods_list是否已经选中过该商品了*/
function handleIsSelectedGoods(item: IGoodsList) {
  for (let i = 0; i < form.goods_list.length; i++) {
    if (form.goods_list[i].goods_id === item.id) {
      return true;
    }
  }
  return false;
}
/* 为活动添加商品 */
function handleAddGoodsList(data: IGoodsList) {
  form.goods_list.push({
    goods_id: data.id,
    goods_name: data.goods_name,
    original_img: data.original_img,
    sort: 0,
    commission_rate: 0,
    id: 0,
    isPermitDelete: true
  });
}

/* 删除达人抖音号 */
function handleClose(tag: string) {
  /* 应为必定存在 无需判断-1的情况 */
  form.douyin_id_list.splice(form.douyin_id_list.indexOf(tag), 1);
}
/* 确定达人抖音号 */
function handleInputConfirm() {
  /* 判断是否重复 */
  if (form.douyin_id_list.includes(inputValue.value)) {
    ElMessage.warning("达人抖音号重复，请重新输入");
    return;
  }
  if (deleteDouyinIdList.value.includes(inputValue.value)) {
    ElMessage.warning("达人抖音号已取消该计划，请重新输入");
    return;
  }

  if (inputValue.value) {
    form.douyin_id_list.push(inputValue.value);
  }
  inputVisible.value = false;
  inputValue.value = "";
}
/* 显示input标签 */
function handleShowInput() {
  inputVisible.value = true;
  nextTick(() => {
    saveTagInput.value?.focus();
  });
}

handleGetMallCategory();
</script>

<style lang="scss" scoped>
/* 修改select的盒模型 */
.el-select {
  display: block;
}
/* 底部按钮居中 */
.footer-center {
  margin: 10px 0;
  text-align: center;
}

/* tag相关 start */
.tags-info {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-right: 10px;
}
.input-new-tag {
  width: 140px;
}
/* end */
</style>
